// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: "vistcx-i7q7h"
})
const DB = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  //获取openid
  const wxContext = cloud.getWXContext()
  // 获取当前日期
  const timestamp = Date.parse(new Date())
  const nowDate = new Date(timestamp)
  const year = nowDate.getFullYear();
  const month = (nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1);
  const day = (nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate.getDate());
  const date = year + '-' + month + '-' + day
  // 查询数据库
  let status = -1
  return await DB.collection('plugin').where({ _openid: wxContext.OPENID, date: date, id: event.id }).get().then(res => {
    if (res.data.length == 0) {
      return DB.collection('plugin').add({
        data: {
          id: event.id,
          date: date,
          _openid: wxContext.OPENID
        }
      }).then(res => {
        const _ = DB.command
        return DB.collection('sightInfo').where({ id: event.id}).update({
          data: {
            num: _.inc(1)
          }
        }).then(res=> {
          return 200 //打卡成功
        }).catch(res=> {
          return 202 //打卡失败
        })
      }).catch(err => {
        console.log(err)
        return 202 //打卡失败
      })
    } else {
      return 201 //已打卡
    }
  }).catch(err=>{
    return 202 //打卡失败
  })
}